<template>
  <div class="sn-common-container ">
    <div class="prcoss-container">
      <header>
        <div class="sn-flex sn-row-center hidden-sm-and-down">
          <el-input v-model="searchValue" placeholder="输入角色名称进行筛选" style="width: 200px" clearable
            @keyup.enter.native="currentChange(1)" />
          <el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-search"
            @click="currentChange(1)">
            搜索
          </el-button>
          <el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-plus"
            @click="addRoleBtnClick()">
            添加新角色
          </el-button>
        </div>
        <div class="hidden-sm-and-up">
          <el-input v-model="searchValue" placeholder="输入角色名称进行筛选" style="width: 200px" clearable
            @keyup.enter.native="currentChange(1)" />
          <el-button style="margin-left: 4px" type="primary" class="sn-btn" icon="el-icon-search"
            @click="currentChange(1)">
          </el-button>
          <el-button style="margin-left: 4px" type="primary" class="sn-btn" @click="addRoleBtnClick()">
            添加
          </el-button>
        </div>
      </header>
      <section>
        <global-table style="margin-top: 20px;" :pageIndex="currentPage" :pageSize="pageSize" :headerData="initData"
          :data="tabelData" :isFullScreen="false" :operateW="300">
          <template #operate="scope">
            <el-button type="primary"  size="mini" @click="ediRoleBtnClick(scope.row)">修改</el-button>
            <el-button type="warning"  size="mini" @click="editRolePower(scope.row.id)">配置权限</el-button>
            <el-button type="primary" class="sn-btn" icon="el-icon-delete" size="mini" @click="delRoleFn(scope.row.id)">删除</el-button>
          </template>
        </global-table>
      </section>
      <footer>
        <el-pagination @current-change="currentChange" :current-page.sync="currentPage" :page-size="pageSize"
          layout="prev, pager, next, jumper" :pager-count="7" class="sn-pagination" hide-on-single-page
          style="text-align: center;" :total="totalNum" background>
          >
        </el-pagination>
      </footer>
    </div>
    <!-- 编辑或新增弹窗 -->
    <el-dialog :visible.sync="editRoleDialog" class="sn-default-dialog" width="360px" @close="roleDialogClose()">
      <div class="sn-title" slot="title">编辑角色</div>
      <div v-loading="editRoleLoading">
        <p style="margin-top: 0;">角色名称：</p>
        <el-input v-model="editRoleName" placeholder="请输入角色名称" style=""></el-input>
        <p>关联员工：</p>
        <div class="sn-flex" style="flex-wrap: wrap;width: 100%;overflow: hidden;">
          <p v-show="userTags.length < 1">已有员工列表为空，马上去添加添加员工吧！</p>
          <el-tag :key="JSON.parse(tag).id" v-for="(tag,index) in userTags" closable :disable-transitions="false" @close="delUser(index)">
            {{ JSON.parse(tag).name }}
          </el-tag>
        </div>
        <p>
          <el-button type="primary" size="medium " class="sn-btn" icon="el-icon-plus" @click="addEmployeeFlag = false;"
            v-show="addEmployeeFlag">添加员工</el-button>
          <el-button type="primary" size="medium " class="sn-btn" icon="el-icon-close" @click="addEmployeeFlag = true;"
            v-show="!addEmployeeFlag">收起</el-button>
        </p>
        <el-card shadow="always" :body-style="{ padding: '20px' }" v-show="!addEmployeeFlag">
          <div slot="header">
            <el-row type="flex" justify="center">
              <el-input v-model="searchEmployeeName" @input="searchStaffListDebonce" placeholder="输入员工名称进行添加"></el-input>
            </el-row>
          </div>
          <div class="card-body-scorll" v-loading="staffLoadingFlag">
            <p style="text-align:center;" v-show="userList.length === 0">没有符合条件的员工</p>
            <el-checkbox-group v-model="userTags">
              <el-checkbox border v-for="(item,index) in userList" :key="index"
                :label="item">{{JSON.parse(item).name }} </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-card>
        <p style="text-align: center;">
          <el-button type="primary" size="medium" class="sn-btn" @click="saveRoleInfoFn()">保存</el-button>
          <el-button size="medium" @click="editRoleDialog = false">取消</el-button>

        </p>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="roleTreeDialog" width="360px" class="sn-default-dialog">
      <div class="sn-title" slot="title">配置权限</div>
      <div v-loading="editRoleLoading">
        <el-tree :data="permissionTree" show-checkbox ref="permissionTree" node-key="id" class="permission-tree"
          :default-checked-keys="defaultPermissionChecked" :default-expand-all="true" :props="defaultProps">
        </el-tree>
        <el-row type="flex" justify="center" style="margin-top:50px;">
          <el-button type="primary" size="medium " @click="saveRolePower()">保存</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import GlobalTable from '@/components/GlobalTable';
import { GetRolesPage, GetEmployeePage, ModifyMenusForRole,GetMenus,GetRole,AddRole, UpdateRole,DeleteRole } from '@/api/accessmanage';
import { guid } from '@/utils'
export default {
  components: { GlobalTable },
  data() {
    return {
      tabelData: [],
      initData: [
        {
          label: '角色名称',
          value: 'name',
          id: guid(),
        }
      ],
      currentPage: 1,
      pageSize: 10,
      totalNum: 0,
      searchValue: '',
      editRoleDialog: false,
      editRoleName: '',
      userTags: [],
      userList: [],
      addEmployeeFlag: true,
      staffLoadingFlag: false,
      searchEmployeeName: '',
      editRoleLoading: false,
      roleTreeDialog: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
      defaultPermissionChecked: [],
      roleId: '',
      permissionTree: [],
    }
  },
  created() {
    this.getDataListFn();
  },
  methods: {
    delRoleFn(id){
      this.$confirm('您将要删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.loading = true;
          try {
             let res = await DeleteRole({id:id});
             this.loading = false;
             if(res.code === 200){
                this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getDataListFn();
             }else{
               this.$message.error('删除失败，错误信息：'+res.erroMessage);
             }
          } catch (error) {
            this.loading = false;
            this.erroMessageShow(error);
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });  
        });
    },
    //获取角色已配置权限树
    async getTreeByRole(id) {
      this.editRoleLoading = true;
      this.roleId = id;
      let res = await GetRole({ id: id });
      if (res.code === 200) {
        this.defaultPermissionChecked = res.data.menus.map(item=>{return item.id});
      } else {
        this.editRoleLoading = false;
        this.$message.error('获取角色对应权限失败，错误信息：' + res.erroMessage)
      }
    },
    // 点击配置权限按钮 获取权限树
    async editRolePower(id) {
      try {
        await this.getTreeByRole(id);
        let res = await GetMenus();
        this.editRoleLoading = false;
        if (res.code === 200) {
          this.permissionTree = res.data;
          this.roleTreeDialog = true;
        } else {
          this.$message.error('获取权限树失败');
        }
      } catch (error) {
        console.log(error);
        this.editRoleLoading = false;
        this.$message.error('网络请求失败');
      }
    },
    // 保存权限配置
    async saveRolePower() {
      let ary = [];
			let forData = this.$refs.permissionTree.getCheckedKeys(true)
		   forData.forEach(item=>{
			  ary.push(item)
			})
      let params = {
				roleId:this.roleId,
				menuIds:ary
      }
      this.editRoleLoading = true;
      let res = await ModifyMenusForRole(params);
      this.editRoleLoading = false;
      if (res.code === 200) {
        this.roleTreeDialog = false;
      } else {
        this.$message.error('配置权限失败');
      }
    },
    // 保存角色基本信息
    async saveRoleInfoFn() {
      this.editRoleLoading = true;
      let params = {
        name:this.editRoleName,
        employeeIds:this.userTags.map(item=>{return JSON.parse(item).id})
      }
      if(this.roleId!== ''){
        params.id = this.roleId;
        let res = await UpdateRole(params);
        this.editRoleLoading = false;
        if (res.code === 200) {
          this.$message.success('修改角色信息成功');
          this.editRoleDialog  = false;
          this.getDataListFn();
        } else {
          this.$message.error('修改角色失败，错误信息：' + res.erroMessage)
        }
      }else{
        let res = await AddRole(params);
        this.editRoleLoading = false;
        if (res.code === 200) {
          this.$message.success('新建角色信息成功');
          this.editRoleDialog  = false;
          this.getDataListFn();
        } else {
          this.$message.error('新建角色失败，错误信息：' + res.erroMessage)
        }
      }
    },
    // 关闭编辑角色信息窗口
    roleDialogClose() {
      this.editRoleName = '';
      this.userTags = [];
      this.userList = [];
      this.editRoleLoading = false;
      this.roleId ='';
    },
    delUser(index) {
      this.userTags.splice(index, 1);
    },
    //员工搜索框节流处置
    searchStaffListDebonce: _.throttle(async function () {
      this.staffLoadingFlag = true;
      let params = {
        PageIndex: 1,
        PageSize: 100,
        EmployeeName: this.searchEmployeeName,
      };
      if (this.staffName === '') {
        this.staffList = []
        return false;
      } else {
        try {
          let res = await GetEmployeePage(params)
          if (res.code === 200) {
            this.staffLoadingFlag = false;
            if(res.data.list){
              this.userList = res.data.list.map(item=>{
                return  JSON.stringify({name:item.employeeName,id:item.userId})
              });
            }
          } else {
            this.staffLoadingFlag = false;
            this.$message.error('查询失败');
          }
        } catch (error) {
          this.staffLoadingFlag = false;
          this.$message.error('数据请求失败');
        }
      }
    }, 1000),
    addRoleBtnClick() {
      this.editRoleDialog = true;
      this.roleId = '';
    },
    async ediRoleBtnClick(data) {
      this.editRoleDialog = true;
      this.editRoleLoading = true;
      this.roleId = data.id;
      let res = await GetRole({ id: data.id });
      this.editRoleLoading = false;
      if (res.code === 200) {
        this.editRoleName = res.data.name;
        if(res.data.employees){
          this.userTags = res.data.employees.map(item=>{
            return JSON.stringify({name:item.employeeName,id:item.userId});
          })
        }
      } else {
        this.$message.error('获取角色对应权限失败，错误信息：' + res.erroMessage)
      }
    },
    currentChange(val) {
      this.currentPage = val;
      this.getDataListFn();
    },
    async getDataListFn() {
      let params = {
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        name: this.searchValue
      }
      const res = await GetRolesPage(params);
      if (res.code === 200) {
        this.tabelData = res.data.list;
        this.totalNum = res.data.totalCount;
      } else {
        this.tabelData = [];
        this.$message.error('获取角色列表失败，错误信息：' + res.erroMessage);
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.prcoss-container {
  box-sizing: border-box;
  padding: 20px;
  background-color: #fff;
}
</style>